package com.example.jddjxx;

import com.example.jddjxx.selenium.MyWebDriverEventListener;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.events.EventFiringWebDriver;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * google浏览器驱动实例
 *
 * @author DFF
 */
public class ChromeDriver {

    private static volatile EventFiringWebDriver driver;

    private ChromeDriver() {
    }

    @SneakyThrows
    public static EventFiringWebDriver getInstance() {

        if (driver == null) {
            synchronized (ChromeDriver.class) {
                if (driver == null) {

                    final String property = System.getProperty("webdriver.chrome.driver");
                    final String decode = URLDecoder.decode(property, StandardCharsets.UTF_8.toString());
                    if (StringUtils.isBlank(decode)){
                        throw new IllegalArgumentException("请设置-Dwebdriver.chrome.driver");
                    }
//                    System.setProperty("webdriver.chrome.driver", decode);
                    ChromeOptions options = new ChromeOptions();
                    //让窗口最大化
                    options.addArguments("start-maximized");
                    options.setPageLoadStrategy(PageLoadStrategy.NORMAL);

                    DesiredCapabilities dc = new DesiredCapabilities();
                    dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR,
                            UnexpectedAlertBehaviour.ACCEPT);

                    options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);
                    driver = new EventFiringWebDriver(new org.openqa.selenium.chrome.ChromeDriver(options)).register(new MyWebDriverEventListener());

                    //所有的findElement方法都会隐式等待0.2s
                    // driver.manage().timeouts().implicitlyWait(200, TimeUnit.MILLISECONDS);
                }
            }
        }

        return driver;
    }

    public static void destroyInstance() {
        if (driver == null) {
            return;
        }
        driver.close();
        driver = null;
    }

}
